package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author stone
 * @date 2022/10/04 16:36
 */
@Service
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate transactionTemplate; //等下注册这个组件

    @Override
    public void transfer(Integer fromId, Integer destId, Integer money) {
        Integer fromMoney = accountMapper.selectMoneyById(fromId);
        Integer destMoney = accountMapper.selectMoneyById(destId);

        fromMoney -= money;
        destMoney += money;

        Integer finalFromMoney = fromMoney;
        Integer finalDestMoney = destMoney;
        // 匿名内部类 Proxy.newProxyInstance(classLoader,interfaces,new InvocationHandler)
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                accountMapper.updateMoneyById(fromId, finalFromMoney);
                if (money > 100) {
                    int i = 1 / 0;
                }

                accountMapper.updateMoneyById(destId, finalDestMoney);
                return null;
            }
        });
    }
}
